<template>
	<view class="app-statistics-app">
		<Tips title="小贴士" :des="des" />
		<view class="statistics-wrap" v-if="showPageContent">
			<Tabbar :active="active">
					<TabbarItem @change="() => switcahTable(0)">
						<view class="custom-tabber-item" :class="{'active-tabbar-item': active === 0}">
							<picker mode="date" :value="date" :start="startDate" :end="endDate" @change="bindDateChange">
								<view class="uni-input">{{date}}</view>
							 </picker>
							 <uni-icons type="down" size="16" :color="queryColor(active === 0)"></uni-icons>
						</view>
					</TabbarItem>
					<TabbarItem @change="() => switcahTable(1)"> 
						<view class="custom-tabber-item" :class="{'active-tabbar-item': active === 1}">本周统计</view>
					</TabbarItem>
					<TabbarItem @change="() => switcahTable(2)">
						<view class="custom-tabber-item" :class="{'active-tabbar-item': active === 2}">上周统计</view>
					</TabbarItem>
			</Tabbar>
			<Statistics :statisticsData="statisticsData" @sortByUseTime="sortByUseTime"/>
		</view>
		<view v-else class="loadingHomePage">
			<Empt description="暂无统计信息" />
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref, computed, onMounted } from 'vue'
	import Tips from '@/components/tips/index.vue'
	import Statistics from "@/components/statistics/index.vue";
	import Empt from "@/components/Empt/index.vue"
	 import Tabbar from "@/components/tabbar/index"
	 import TabbarItem from "@/components/tabbar/tabbar-item.vue"
	import { homeServer } from '@/common/index'
	import { useStudentListStore } from "@/stores/useStudentList.js"
	import { urlHelp, mock } from '@/utils/index';
	import { useBound } from "@/hooks/useBound.ts"
	
	const {tipBoundStudent, studentIsEmpt} = useBound();
		
	const studentStore = useStudentListStore();
	const curStd = computed(() => studentStore.currentStudent);
	
	const queryColor = (bool: boolean): string =>  bool ? '#2BC888' : '#ccc'
	
	const showPageContent = ref(false)
	// 设置mock数据
	const setmock = () => {
		const data = JSON.parse(JSON.stringify(mock.APP_USE_TIME.data))
		statisticsData.value = urlHelp.addPercentageToArray(data).map(item => urlHelp.imgAddPrefix(item, 'appImage'));
		showPageContent.value = true
	}
	const statisticsData = ref([]);
	// 应用统计  type: 统计方式(1-按日期统计, 2-统计本周, 3-统计上周)
	const appRecordsStatistics = async () => { 
		const studentId = curStd.value?.id;
		showPageContent.value = false;
		uni.showLoading({
			title:"加载中"
		})
		const types :Array<{value: 0 | 1 | 2, type: 1 | 2 | 3}>= [
			{
				value:0,
				type: 1
			},
			{
				value:1,
				type:2
			},
			{
				value:2,
				type: 3
			},
		]
		const { type, value } = types.find(t => t.value === active.value)
		const params  = {
			studentId,
			type,
		}
		if(value === 0){
			params.date = date.value
		}
		if(!studentIsEmpt || !studentId){
			showPageContent.value = true;
			uni.hideLoading()
			return;
		}
		
		try{
			const {status, data} = await homeServer.appRecordsStatistics(params);
			if(status === '200'){
				statisticsData.value = urlHelp.addPercentageToArray(data).map(item => urlHelp.imgAddPrefix(item, 'appImage'));
				console.log("要走到这里来", statisticsData.value)
				showPageContent.value = true
				uni.hideLoading()
			}
		}catch(e){
			console.log(e)
			//TODO handle the exception
		}
		showPageContent.value = true;
		uni.hideLoading()
	}
	
	const sortByUseTime = () => {
		if(statisticsData.value.length === 0 || statisticsData.value.length == 1){
			return;
		}
		const useTime = 'useTime'
	    const cur_max_sort = statisticsData.value[0][useTime] > statisticsData.value[1][useTime]; 
		function sortArrayByUseTime(arr, ascending = true) {  
		    // ascending 参数默认为 true，表示从小到大排序  
		    // 如果设置为 false，则表示从大到小排序  
		    arr.sort((a, b) => {  
		        if (ascending) {  
		            // 从小到大排序  
		            return a.useTime - b.useTime;  
		        } else {  
		            // 从大到小排序  
		            return b.useTime - a.useTime;  
		        }  
		    });  
		    return arr;  
		}  
		if(cur_max_sort){ // 现在是从时间最大到最小排序的，那么需要反过来
			statisticsData.value = sortArrayByUseTime(statisticsData.value, true)
		} else {// 现在是从时间最小到最大排序的，那么需要反过来
			statisticsData.value = sortArrayByUseTime(statisticsData.value, false)
		}
		
	}
	
	onMounted(() => {
		if(!mock.isLogged()){
			setmock()
		}else {
			appRecordsStatistics()
		}
	})
	
	const des = ref([
		"1.应用统计每15分钟更新一次 。",
		"2.统计有误差，仅作参考，部分App在后台运行也会算在统计时间内。",
		{
			text: '3.使用帮助',
			type: 'statistics'
		}
	])
	const active = ref(0);
	const onChange = ({detail}:any) => {
		active.value = detail;
		if(Number(detail) !== 0){
		  appRecordsStatistics()
		} 
	}
	const switcahTable = (n: number) => {
		onChange({detail: n})
	}
	 const getDate = (type) =>{
		const date = new Date();
		let year = date.getFullYear();	
		let month: string | number = date.getMonth() + 1;
		let day: number | string = date.getDate();

		if (type === 'start') {
			year = year - 60;
		} else if (type === 'end') {
			year = year + 2;
		}
		month = month > 9 ? month : '0' + month;
		day = day > 9 ? day : '0' + day;
		return `${year}-${month}-${day}`;
	 };
	 const date = ref(getDate({format: true}));
	 const startDate = computed(() => getDate('start'))
	 const endDate = computed(() => getDate('end'));
	 const bindDateChange = ({detail}) => {
		 if(!mock.isLogged()){
			tipBoundStudent();
			return
		}
		 		
		 date.value = detail.value;
		 console.log('确定了时间', detail)
		 appRecordsStatistics()
	 }
</script>
<style lang="scss">
	page {
		background-color: #f5f9fa;
	}
</style>

<style lang="scss" scoped>
	.app-statistics-app{
		.statistics-wrap{
			margin-top: 40upx;
		}
	}
</style>


<style  lang="scss">
	.loadingHomePage{
		background-color: rgba(0, 0, 0, 0.01);
		width: 100vw;
		height: calc(100vh - 300upx);
		display: flex;
		justify-content: center;
		align-items: center;
	}
	
	.statistics-wrap{
		.van-tabbar{
			padding:0;
		}
		.custom-tabber-item{
			display: flex;
			justify-content: center;
			align-items: center;
			padding-bottom: 20upx;
			font-size: 30upx;
		}
		.active-tabbar-item{
			border-bottom: 5upx solid #2BC888;
			color: #2BC888;
		}
	}

</style>